package com.hdcircles.autoform.presenter;

import com.hdcircles.autoform.base.RxPresenter;
import com.hdcircles.autoform.model.bean.User;
import com.hdcircles.autoform.model.http.HttpResponse;
import com.hdcircles.autoform.model.http.RetrofitHelper;
import com.hdcircles.autoform.presenter.contract.LoginContract;
import com.hdcircles.autoform.util.RxUtil;
import com.hdcircles.autoform.util.SharedPreferenceUtil;

import javax.inject.Inject;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by hdcircles on 2016/11/10.
 */

public class LoginPresenter extends RxPresenter<LoginContract.View> implements LoginContract.Presenter {

    private RetrofitHelper retrofitHelper;

    @Inject
    public LoginPresenter(RetrofitHelper retrofitHelper){
        this.retrofitHelper=retrofitHelper;
    }

    @Override
    public void login(final String email, String password) {
        User u=new User();
        u.setEmail(email);
        u.setPassword(password);
        Subscription subscription=retrofitHelper.login(u)
                .compose(RxUtil.<HttpResponse<String>>rxScheduleHelper())
                .compose(RxUtil.<String>handleResult())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mView.loginSuccess(s);
                        SharedPreferenceUtil.setUserEmail(email);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mView.showError("登录错误");
                    }
                });
        addSubscribe(subscription);
    }
}
